package examples;

import java.util.List;
import java.util.Random;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * CopyOnWriteArrayList的线程安全测试，CopyOnWriteArraySet参考
 * 
 * 例子思路：
 * 开启100个线程，每次向List中插入一个随机数
 * 当List使用的是CopyOnWriteArrayList时，可以正确运行，说明CopyOnWriteArrayList是线程安全的
 * 若将List使用的是ArrayList时，会出现ConcurrentModificationException错误，说明ArrayList是非线程安全的
 * 
 * 
 * 
 * java.util.ConcurrentModificationException
 * @author yecheng
 *
 */

public class CopyOnWriteArrayListDemo {
	
	public static void main(String[] args){
		
		ExecutorService executorService = Executors.newCachedThreadPool();//过了60秒回收，不限制大小
		
		final List<Integer> copyOnWriteArrayList = new CopyOnWriteArrayList<Integer>();
		//修改为ArrayList报异常ConcurrentModificationException
//		final List<Integer> copyOnWriteArrayList = new ArrayList<Integer>();
		
		final Random random = new Random();
		
		Runnable runnable = new Runnable(){
			@Override
			public void run() {
				copyOnWriteArrayList.add(random.nextInt(20));
				System.out.println(copyOnWriteArrayList.toString());
			}
		};
		
		try{
			for(int i=0;i<100;i++){
				executorService.execute(runnable);
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			executorService.shutdown();
		}
		
	}

}
